/*
 * The MIT License
 *
 * Copyright (c) 2011 Takahiro Hashimoto
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.xiyuan.smartutils.client.http.ws;

import com.xiyuan.smartutils.client.exception.WebSocketException;
import com.xiyuan.smartutils.constants.WebSocketConstants;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.List;

/**
 * The Interface WebSocket.
 *
 * @author xiyuan
 */
@SuppressWarnings({"AlibabaAvoidStartWithDollarAndUnderLineNaming", "CharsetObjectCanBeUsed"})
public interface WebSocket extends WebSocketConstants {
    public static final Charset _UTF8_C_ = Charset.forName("UTF-8");
    
    /**
     * Send.
     *
     * @param packet the packet
     * @throws WebSocketException the web socket exception
     */
    public void send(WebSocketPacket packet) throws WebSocketException;
    
    
    /**
     * Gets the location.
     *
     * @return the location
     */
    public URI getLocation();
    
    /**
     * Gets the endpoint.
     *
     * @return the endpoint
     */
    public String getPath();
    
    public String getOrigin();
    
    public String[] getProtocols();
    
    /**
     * get connection request header
     *
     * @param name header name
     * @return first header value
     */
    public String getHeader(String name);
    
    /**
     * get connection request header
     *
     * @param name header name
     * @return header values
     */
    public List<String> getHeaders(String name);
    
    /**
     * Close.
     */
    public void close();
    
    /**
     * Send.
     *
     * @param buffer the ByteBuffer
     * @throws WebSocketException the web socket exception
     */
    default void send(ByteBuffer buffer) throws WebSocketException {
        send(createPacket(buffer));
    }
    
    /**
     * Send.
     *
     * @param bytes the bytes
     * @throws WebSocketException the web socket exception
     */
    default void send(byte[] bytes) throws WebSocketException {
        send(createPacket(bytes));
    }
    
    /**
     * Send.
     *
     * @param text the text
     * @throws WebSocketException the web socket exception
     */
    default void send(String text) throws WebSocketException {
        send(createPacket(text));
    }
    
    /**
     * Send ping.
     *
     * @throws WebSocketException the web socket exception
     */
    default void ping() throws WebSocketException {
        send(createPing());
    }
    
    /**
     * Send pong.
     *
     * @throws WebSocketException the web socket exception
     */
    default void pong() throws WebSocketException {
        send(createPong());
    }
    
    
    /**
     * Creates the frame.
     *
     * @param obj the obj
     * @return the frame
     * @throws WebSocketException the web socket exception
     */
    default WebSocketPacket createPacket(Serializable obj) throws IllegalArgumentException {
        try {
            if (obj instanceof String) {
                return new WebSocketPacket((String) obj, TEXT);
            }
            
            if (obj.getClass() == byte[].class) {
                return new WebSocketPacket((byte[]) obj, BIN);
            }
            
            if (obj == null) {
                return new WebSocketPacket((byte[]) null, BIN);
            }
            
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bao);
            oos.writeObject(obj);
            
            return createPacket(bao.toByteArray());
        }
        catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
    
    /**
     * Creates the frame.
     *
     * @param bytes the byte array
     * @return the frame
     */
    default WebSocketPacket createPacket(byte[] bytes) {
        return new WebSocketPacket(bytes, BIN);
    }
    
    /**
     * Creates the frame.
     *
     * @param buffer the ByteBuffer
     * @return the frame
     * @throws WebSocketException the web socket exception
     */
    default WebSocketPacket createPacket(ByteBuffer buffer) {
        byte[] bytes = buffer == null ? null : new byte[buffer.remaining()];
        if (buffer != null) {buffer.get(bytes);}
        return createPacket(bytes);
    }
    
    /**
     * Creates the frame.
     *
     * @param str the str
     * @return the frame
     */
    default WebSocketPacket createPacket(String str) {
        return new WebSocketPacket(str, Opcode.TEXT);
    }
    
    
    /**
     * create Ping message
     */
    default WebSocketPacket createPing() {
        return new WebSocketPacket(Opcode.PING);
    }
    
    /**
     * create Pong message
     */
    default WebSocketPacket createPong() {
        return new WebSocketPacket(Opcode.PONG);
    }
    
}
